package com.huynv.socialphotos;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.PorterDuff.Mode;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;

import com.huynv.socialphotos.BaseAlbumDirFactory;
import com.huynv.socialphotos.FroyoAlbumDirFactory;
import com.huynv.socialphotos.AlbumStorageDirFactory;
import com.huynv.socialphotos.R;
//import android.R;

import android.graphics.Bitmap.Config;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.graphics.BitmapShader;
import android.graphics.PorterDuffColorFilter;


import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.net.*;

import java.text.SimpleDateFormat;
import java.util.*;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

public class MainActivity extends Activity {
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 2;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	private Uri fileUri;
	private String mCurrentPhotoPath=null;
	ImageView mainImage,original,thumb1,thumb2,thumb3,thumb4,thumb5,thumb6,thumb7,thumb8,thumb9,thumb10;
	Bitmap bmThumb1,bmThumb2,bmThumb3,bmThumb4,bmThumb5,bmThumb6,bmThumb7,bmThumb8,bmThumb9,bmThumb10;
	Button openGallery;
	Button effect;
	Bitmap[] thumb=new Bitmap[36];
	private Bitmap mImageBitmap;
	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
	private static final int ACTION_TAKE_PHOTO_S = 1;
	private MainActivity cameraActivity;
	private static final int SELECT_PICTURE = 1;
	private static final Mode[] allTheMode=new Mode[7];
	private static final int lengthMode=allTheMode.length;
	private static Mode fromMode=null,toMode=null;
	private static File currentFile=null;
	private static String currentPhotos=null;
	int i=0;
	int lengthImage=0;
	private GridView gridview;
	private ProgressDialog dialog;
    private Handler progressBarHandler = new Handler();
    private int progressBarStatus = 0;
    private Thread tPr;
    private AlertDialog.Builder alertDialogBuilder;
	private AlertDialog alertDialog;
	private ActionBar actionBar;
	private InterstitialAd adView;
	private static final String AD_UNIT_ID = "ca-app-pub-6575239088642506/1558548874";//"ca-app-pub-6575239088642506/4572279272";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		actionBar = getActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg));
		
		dialog=new ProgressDialog(this);
		allTheMode[0]=Mode.SCREEN;
		allTheMode[1]=Mode.SRC;
		allTheMode[2]=Mode.SRC_OVER;
		allTheMode[3]=Mode.DST_IN;
		allTheMode[4]=Mode.MULTIPLY;
		allTheMode[5]=Mode.DARKEN;
		allTheMode[6]=Mode.OVERLAY;//DST_OUT, OVERLAY co nuoc anh rat dep
				
		cameraActivity=this;
		//Bitmap bp=(Bitmap) BitmapFactory.decodeResource(getResources(), R.drawable.hoa2);
		//Bitmap bp2=(Bitmap) BitmapFactory.decodeResource(getResources(), R.drawable.hoa2);
		//saveImage(bp,bp2,Mode.SRC_OVER,"hoa21SRC_OVERSRC_OVER.jpg");
		//saveImage(bp,bp2,Mode.DST_IN,"hoa22DST_INDST_IN.jpg");
		//saveImage(bp,bp2,Mode.SRC,"hoa23SRCSRC.jpg");
		//saveImage(bp,bp2,Mode.MULTIPLY,"hoa24MULTIPLYMULTIPLY.jpg");
		//saveImage(bp,bp2,Mode.XOR ,"hoa25XORXOR.jpg");
		mainImage = (ImageView)findViewById(R.id.mainImage);
		gridview = (GridView) findViewById(R.id.gridview);
	    
		openGallery = (Button)findViewById(R.id.openGallery);	
		mImageBitmap = null;
		Button.OnClickListener mTakePicOnClickListener = 
				new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					//showProcess();
					//new showOpenPicTask().execute(String.valueOf(SELECT_PICTURE));
					gridview.setVisibility(View.INVISIBLE);
					open(SELECT_PICTURE);//dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
				}
			};
		setBtnListenerOrDisable( 
				openGallery, 
					mTakePicOnClickListener,
					MediaStore.ACTION_IMAGE_CAPTURE
		);
		effect = (Button)findViewById(R.id.effect);		
		effect.setOnClickListener(new OnClickListener() {
		    public void onClick(View v) {
		        // TODO Auto-generated method stub
		    	    if (mCurrentPhotoPath==null) return;
		    		showProcess();
		    		//loadEffect();
		    		//hideProcess();
		    		new showOpenPicTask().execute("");
		    		
		    }
		 });
		effect.setVisibility(View.INVISIBLE);	
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}
		adView = new InterstitialAd(this);
		//adView.setAdSize(AdSize.BANNER);
		adView.setAdUnitId(AD_UNIT_ID);
		adView.setAdListener(new AdListener() {
		      @Override
		      public void onAdLoaded() {
		        Log.e("onAdLoadedonAdLoadedonAdLoaded", "onAdLoaded");
		      
		      }

		      @Override
		      public void onAdFailedToLoad(int errorCode) {
		        String message = String.format("onAdFailedToLoad (%s)", getErrorReason(errorCode));
		        Log.e("onAdFailedToLoadonAdFailedToLoad", message);
		      }
		    });
//		RelativeLayout rl = new RelativeLayout(this);
//		RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
//				RelativeLayout.LayoutParams.FILL_PARENT,
//				RelativeLayout.LayoutParams.WRAP_CONTENT);
//		lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//		RelativeLayout layout = (RelativeLayout) findViewById(R.id.rlMainAll);
//		layout.addView(adView, lay);
		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);
	}
	 /** Gets a string error reason from an error code. */
	  private String getErrorReason(int errorCode) {
	    String errorReason = "";
	    switch(errorCode) {
	      case AdRequest.ERROR_CODE_INTERNAL_ERROR:
	        errorReason = "Internal error";
	        break;
	      case AdRequest.ERROR_CODE_INVALID_REQUEST:
	        errorReason = "Invalid request";
	        break;
	      case AdRequest.ERROR_CODE_NETWORK_ERROR:
	        errorReason = "Network Error";
	        break;
	      case AdRequest.ERROR_CODE_NO_FILL:
	        errorReason = "No fill";
	        break;
	    }
	    return errorReason;
	  }
	// Invoke displayInterstitial() when you are ready to display an interstitial.
	public void displayInterstitial() {
		Log.e("displayInterstitial", "ok");
	   //if (adView.isLoaded()) {
		   Log.e("displayInterstitial", "ok1");
	    	adView.show();
	    	Log.e("displayInterstitial", "ok2");
	   //}
	}
	private class showOpenPicTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	
            	loadEffect();           	
        		Log.e("showOpenPicTask", "ok2");
        		//boolean result=
                return "1";
            } catch (Exception e) {
            	Log.e("showNewsSearchFromUrlTask", "can not download");
            	tPr.interrupt();
            	progressBarStatus=-1;
            	//dialog.setProgress(0);
            	//dialog.cancel();
            	dialog.dismiss();
            	//showExtProgram("Alert","Can not open this image");
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        @Override
        protected void onPreExecute(){
        	//showProcess();
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	try{
        		//if(dialog!=null) 
        		Log.e("onPostExecute", "ok1");
        		showThumbailEffect();
        		Log.e("onPostExecute", "ok2");
	        	tPr.interrupt();
	        	progressBarStatus=-1;
	        	dialog.setProgress(0);
	        	//dialog.cancel();
	   			dialog.dismiss();
	   			displayInterstitial();
	   			Log.e("onPostExecute", "ok3");
        	}catch(Exception ex){
        		
        	}
        	if (result.equals("0")){ 
        		//Log.e("onPostExecute", "can not download");
        		showExtProgram("Alert","Can not open this image!");
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
public void showExtProgram(String title,String message){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

    	// 2. Chain together various setter methods to set the dialog characteristics
    	builder.setMessage(message)
    	       .setTitle(title)
    	       .setCancelable(false)
			   .setPositiveButton("OK",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity							
						//MainActivity.this.finish();
				    	//System.exit(0);
					}
				 });

    	// 3. Get the AlertDialog from create()
    	alertDialog= builder.create();
    	alertDialog.show();
//    	int duration = Toast.LENGTH_SHORT;	
//		Toast toast = Toast.makeText(context, message, duration);
//		toast.show();
	}
	public void hideProcess(){
		//loading=false;
		tPr.interrupt();
		progressBarStatus=-1;
		dialog.setProgress(0);
		//dialog.cancel();
		dialog.dismiss();
	}
	public void showProcess(){
		dialog.setMessage("Loading...");
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(100);
		//dialog.setIndeterminate(true);
		dialog.show();

	   final int totalProgressTime = 100;
	   progressBarStatus=0;
	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(200);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
	}
	public void open(int code){
				//showProcess();
				fromMode=null;
				toMode=null;
				mCurrentPhotoPath=null;
	        	Intent intent = new Intent();
	            intent.setType("image/*");
	            intent.setAction(Intent.ACTION_GET_CONTENT);
	            startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	            
	        
		
        //showProcess();
		  //mCurrentPhotoPath = fileUri.getAbsolutePath();
//		  intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fileUri));
	      //intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
	      //Log.e("Image saved", mCurrentPhotoPath);
	      //startActivityForResult(intent,code);
	   }
//	@Override
//	protected void onPostExecute(){
//		super.onPostExecute();
//		hideProcess();  
//    } 
	 @Override
	   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	      // TODO Auto-generated method stub
		   Log.e("onActivityResult", String.valueOf(requestCode)+"-"+String.valueOf(resultCode));
		   //showProcess();
		   if (resultCode == RESULT_OK) {
	            if (requestCode == SELECT_PICTURE) {
	                Uri selectedImageUri = data.getData();
	                mCurrentPhotoPath = getPath(selectedImageUri);	
	                effect.setVisibility(View.VISIBLE);
	                originalPic();//load to main image	                               
	                //setPicOriginal(original);
	                
	        	    
//	                setPic(thumb1,Mode.SCREEN,Mode.SRC,bmThumb1);
//	                setPic(thumb2,Mode.SCREEN,Mode.SRC_OVER,bmThumb2);
//	                setPic(thumb3,Mode.SCREEN,Mode.DST_IN,bmThumb3);
//	                setPic(thumb4,Mode.SCREEN,Mode.MULTIPLY,bmThumb4);
//	                setPic(thumb5,Mode.SCREEN,Mode.XOR,bmThumb5);
//	                
//	                setPic(thumb6,Mode.SCREEN,Mode.SCREEN,bmThumb6);
//	                setPic(thumb7,Mode.MULTIPLY,Mode.SCREEN,bmThumb7);
//	                setPic(thumb8,Mode.DST_IN,Mode.DST_IN,bmThumb8);
//	                setPic(thumb9,Mode.MULTIPLY,Mode.MULTIPLY,bmThumb9);
//	                setPic(thumb10,Mode.XOR,Mode.XOR,bmThumb10);
	                
	                //setPic(thumb3,Mode.DST_IN);
	                Log.e("onActivityResult,mCurrentPhotoPath=",mCurrentPhotoPath);
	            }
	        }
		   //hideProcess();
	   }
	 private void loadEffect(){
		 Log.e("loadEffect", mCurrentPhotoPath);
		 lengthImage=0;
         thumb=new Bitmap[35];
         //1
         for(i=1;i<=lengthMode;i++){
             	int j=(i-1)/lengthMode;
         		int jj=(i-1)%lengthMode;
         		thumb[i-1]=getPic(allTheMode[j],allTheMode[jj]);	            		
         }	                
         lengthImage+=(i-1);
         //2
         for(i=1;i<=lengthMode;i++){	                	
     		int jj=(i-1)%lengthMode;
     		thumb[lengthImage+i-1]=getPic(allTheMode[3],allTheMode[jj]);	            		
         }
         lengthImage+=i-1;
         //3
         for(i=1;i<=lengthMode;i++){	                	
     		int jj=(i-1)%lengthMode;
     		thumb[lengthImage+i-1]=getPic(allTheMode[4],allTheMode[jj]);	            		
         }
         lengthImage+=i-1;
         //4
         for(i=1;i<=lengthMode;i++){	                	
     		int jj=(i-1)%lengthMode;
     		thumb[lengthImage+i-1]=getPic(allTheMode[5],allTheMode[jj]);	            		
         }
         lengthImage+=i-1;
//         //5
         for(i=1;i<=lengthMode;i++){	                	
     		int jj=(i-1)%lengthMode;
     		thumb[lengthImage+i-1]=getPic(allTheMode[6],allTheMode[jj]);	            		
         }
         lengthImage+=i-1;
         //hideProcess();
         Log.e("DoneDoneloadEffect", mCurrentPhotoPath);
         
	 }
	 private void showThumbailEffect(){
		
		 gridview.setVisibility(View.VISIBLE);
		 gridview.setAdapter(new ImageAdapter(this,thumb));
 	     gridview.setOnItemClickListener(new OnItemClickListener() {
// 	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// 	            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
// 	        }
				@Override
				public void onItemClick(AdapterView<?> parent,
						View view, int position, long id) {
					// TODO Auto-generated method stub
					//mainImage.setImageBitmap(thumb[position]);
					int j=position/lengthMode;
         		int jj=position%lengthMode;
         		Log.e("click vao day nhe", String.valueOf(j)+"---"+String.valueOf(jj));
         		if (j<1){
         			setPic(allTheMode[j],allTheMode[jj]);
         			fromMode=allTheMode[j];
         			toMode=allTheMode[jj];
         		}else if (j<2){
         			setPic(allTheMode[3],allTheMode[jj]);
         			fromMode=allTheMode[3];
         			toMode=allTheMode[jj];
         		}else if (j<3){
         			setPic(allTheMode[4],allTheMode[jj]);
         			fromMode=allTheMode[4];
         			toMode=allTheMode[jj];
					}else if (j<4){
         			setPic(allTheMode[5],allTheMode[jj]);
         			fromMode=allTheMode[5];
         			toMode=allTheMode[jj];
         		}
					else if (j<5){
         			setPic(allTheMode[6],allTheMode[jj]);
         			fromMode=allTheMode[6];
         			toMode=allTheMode[jj];
         		}
				}
 	    });
	 }
	 /**
	     * helper to retrieve the path of an image URI
	     */
	    public String getPath(Uri uri) {
	            // just some safety built in 
	            if( uri == null ) {
	                // TODO perform some logging or show user feedback
	                return null;
	            }
	            // try to retrieve the image from the media store first
	            // this will only work for images selected from gallery
	            String[] projection = { MediaStore.Images.Media.DATA };
	            Cursor cursor = managedQuery(uri, projection, null, null, null);
	            if( cursor != null ){
	                int column_index = cursor
	                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	                cursor.moveToFirst();
	                return cursor.getString(column_index);
	            }
	            // this is our fallback here
	            return uri.getPath();
	    }
	    
	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list =
			packageManager.queryIntentActivities(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	private void setBtnListenerOrDisable( 
			Button btn, 
			Button.OnClickListener onClickListener,
			String intentName
	) {
		if (isIntentAvailable(this, intentName)) {
			btn.setOnClickListener(onClickListener);        	
		} else {
			//btn.setText( 
				//getText(R.string.cannot).toString() + " " + btn.getText());
			btn.setClickable(false);
		}
	}
	
	
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
				//getOutputMediaFile(imageFileName);//File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
		Log.e("createImageFile", imageF.getAbsolutePath());
		return imageF;
	}
	/* Photo album for this application */
	private String getAlbumName() {
		return getString(R.string.album_name);
	}
	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			
			storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());

			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()){
						Log.e("CameraSample", "failed to create directory");
						return null;
					}
				}
			}
			
		} else {
			Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
		}
		
		return storageDir;
	}
	private File setUpPhotoFile() throws IOException {
		
		File f = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();
		
		return f;
	}
		private static final String BITMAP_STORAGE_KEY = "viewbitmap";
		private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
	// Some lifecycle callbacks so that the image can survive orientation change
		@Override
		protected void onSaveInstanceState(Bundle outState) {
			outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
			//outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
			outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
			//outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
			super.onSaveInstanceState(outState);
		}

		@Override
		protected void onRestoreInstanceState(Bundle savedInstanceState) {
			super.onRestoreInstanceState(savedInstanceState);
			mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
			//mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
			mainImage.setImageBitmap(mImageBitmap);
			mainImage.setVisibility(
					savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? 
							ImageView.VISIBLE : ImageView.INVISIBLE
			);
//			mVideoView.setVideoURI(mVideoUri);
//			mVideoView.setVisibility(
//					savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ? 
//							ImageView.VISIBLE : ImageView.INVISIBLE
//			);
		}
		
	  
	   private void handleSmallCameraPhoto(Intent intent) {
		   Bundle extras = intent.getExtras();
    		 mImageBitmap = (Bitmap) extras.get("data");
            //Bitmap bp =(Bitmap) extras.get("data");// setPic();
    		 mainImage.setImageBitmap(mImageBitmap);
		}
	   private void handleBigCameraPhoto() {
		   Log.e("handleBigCameraPhoto", "ok1mCurrentPhotoPath="+mCurrentPhotoPath);
			if (mCurrentPhotoPath != null) {
				Log.e("handleBigCameraPhoto", "ok2");
				//setPic();				
				mCurrentPhotoPath = null;
			}
		   
		}
	   //No effect
	   private void setPicOriginal(ImageView mainBit)
	   {
		   /* Get the size of the ImageView */
			int targetW = mainBit.getWidth();// 300;//mainImage.getWidth();
			int targetH = mainBit.getHeight();//200;//mainImage.getHeight();

			/* Get the size of the image */
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			int photoW = bmOptions.outWidth;
			int photoH = bmOptions.outHeight;
			
			/* Figure out which way needs to be reduced less */
			int scaleFactor = 1;
			if ((targetW > 0) && (targetH > 0)) {
				scaleFactor = Math.min(photoW/targetW, photoH/targetH)+1;	
			}
			Log.e("setPic", "scaleFactor="+String.valueOf(scaleFactor)+",photoW="+String.valueOf(photoW)+",targetW="+String.valueOf(targetW)); 
			/* Set bitmap options to scale the image decode target */
			bmOptions.inJustDecodeBounds = false;
			bmOptions.inSampleSize = scaleFactor;//scaleFactor;
			bmOptions.inPurgeable = true;
			//bmOptions.inScreenDensity=true;
			/* Decode the JPEG file into a Bitmap */
			Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			//bitmap = Bitmap.createScaledBitmap(bitmap, 300, 200, false);
			Log.e("setPic", "ok");
			//mImageBitmap = bitmap;
            //Bitmap bp =(Bitmap) extras.get("data");// setPic();
			//mainImage.setImageBitmap(bitmap);
			mainBit.setImageBitmap(bitmap);
			//output=result;
    		Log.e("setPic", "ok1"); 
			//return result;
	   }
	   private void setPic(PorterDuff.Mode modeOut,PorterDuff.Mode modeMain)
	   {
		   /* Get the size of the ImageView */
			int targetW = mainImage.getWidth();// 300;//mainImage.getWidth();
			int targetH = mainImage.getHeight();//200;//mainImage.getHeight();

			/* Get the size of the image */
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			int photoW = bmOptions.outWidth;
			int photoH = bmOptions.outHeight;
			
			/* Figure out which way needs to be reduced less */
			int scaleFactor = 1;
			if ((targetW > 0) && (targetH > 0)) {
				scaleFactor = Math.min(photoW/targetW, photoH/targetH)+1;	
			}
			//Log.e("setPic", "scaleFactor="+String.valueOf(scaleFactor)+",photoW="+String.valueOf(photoW)+",targetW="+String.valueOf(targetW)); 
			/* Set bitmap options to scale the image decode target */
			bmOptions.inJustDecodeBounds = false;
			bmOptions.inSampleSize = scaleFactor;//scaleFactor;
			bmOptions.inPurgeable = true;
			//bmOptions.inScreenDensity=true;
			/* Decode the JPEG file into a Bitmap */
			Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			Bitmap bitmap2 = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			Bitmap result;
			//bitmap = Bitmap.createScaledBitmap(bitmap, 300, 200, false);
			//Log.e("setPic", "ok");
			//mImageBitmap = bitmap;
            //Bitmap bp =(Bitmap) extras.get("data");// setPic();
			result=MapImage(bitmap,bitmap2,modeOut,modeMain);
			//mainImage.setImageBitmap(bitmap);
			mainImage.setImageBitmap(result);
			//output=result;
    		//Log.e("setPic", "ok1"); 
			//return result;
	   }
	   private String savePic(PorterDuff.Mode modeOut,PorterDuff.Mode modeMain)
	   {
		   /* Get the size of the ImageView */
			int targetW = mainImage.getWidth();// 300;//mainImage.getWidth();
			int targetH = mainImage.getHeight();//200;//mainImage.getHeight();

			/* Get the size of the image */
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			int photoW = bmOptions.outWidth;
			int photoH = bmOptions.outHeight;
			
			/* Figure out which way needs to be reduced less */
			int scaleFactor = 1;
			if ((targetW > 0) && (targetH > 0)) {
				scaleFactor = Math.min(photoW/targetW, photoH/targetH)+1;	
			}
			//Log.e("setPic", "scaleFactor="+String.valueOf(scaleFactor)+",photoW="+String.valueOf(photoW)+",targetW="+String.valueOf(targetW)); 
			/* Set bitmap options to scale the image decode target */
			bmOptions.inJustDecodeBounds = false;
			bmOptions.inSampleSize = scaleFactor;//scaleFactor;
			bmOptions.inPurgeable = true;
			//bmOptions.inScreenDensity=true;
			/* Decode the JPEG file into a Bitmap */
			Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			Bitmap bitmap2 = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			Bitmap result;
			//bitmap = Bitmap.createScaledBitmap(bitmap, 300, 200, false);
			//Log.e("setPic", "ok");
			//mImageBitmap = bitmap;
            //Bitmap bp =(Bitmap) extras.get("data");// setPic();
			result=MapImage(bitmap,bitmap2,modeOut,modeMain);
			
			return storeImage(result);
			//mainImage.setImageBitmap(bitmap);
			//mainImage.setImageBitmap(result);
			//output=result;
    		//Log.e("setPic", "ok1"); 
			//return result;
	   }
	   
	   
	   private Bitmap getPic(PorterDuff.Mode modeOut,PorterDuff.Mode modeMain)
	   {
		   /* Get the size of the ImageView */
			int targetW = 85;//mainBit.getWidth();// 300;//mainImage.getWidth();
			int targetH = 85;//mainBit.getHeight();//200;//mainImage.getHeight();

			/* Get the size of the image */
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			int photoW = bmOptions.outWidth;
			int photoH = bmOptions.outHeight;
			
			/* Figure out which way needs to be reduced less */
			int scaleFactor = 1;
			if ((targetW > 0) && (targetH > 0)) {
				scaleFactor = Math.min(photoW/targetW, photoH/targetH)+1;	
			}
			//Log.e("setPic", "scaleFactor="+String.valueOf(scaleFactor)+",photoW="+String.valueOf(photoW)+",targetW="+String.valueOf(targetW)); 
			/* Set bitmap options to scale the image decode target */
			bmOptions.inJustDecodeBounds = false;
			bmOptions.inSampleSize = scaleFactor;//scaleFactor;
			bmOptions.inPurgeable = true;
			//bmOptions.inScreenDensity=true;
			/* Decode the JPEG file into a Bitmap */
			Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			Bitmap bitmap2 = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			Bitmap result;
			//bitmap = Bitmap.createScaledBitmap(bitmap, 300, 200, false);
			//Log.e("setPic", "ok");
			//mImageBitmap = bitmap;
            //Bitmap bp =(Bitmap) extras.get("data");// setPic();
			result=MapImage(bitmap,bitmap2,modeOut,modeMain);
			//mainImage.setImageBitmap(bitmap);
			//mainBit.setImageBitmap(result);
			//output=result;
    		//Log.e("setPic", "ok1"); 
			return result;
	   }
	   private void resizeViewMainImage(Bitmap viewImage){
		   /* Get the size of the ImageView */
			int targetW = mainImage.getWidth();// 300;//mainImage.getWidth();
			int targetH = mainImage.getHeight();//200;//mainImage.getHeight();
			Bitmap bitmap = Bitmap.createScaledBitmap(viewImage, targetW, targetH, false);
			Log.e("setPic", "ok");
			//mImageBitmap = bitmap;
           //Bitmap bp =(Bitmap) extras.get("data");// setPic();
			//result=saveImage(bitmap,bitmap2,mode);
			mainImage.setImageBitmap(bitmap);
			//mainBit.setImageBitmap(result);
   		Log.e("setPic", "ok1"); 
	   }
	   private void originalPic()
	   {
		   /* Get the size of the ImageView */
			int targetW = mainImage.getWidth();// 300;//mainImage.getWidth();
			int targetH = mainImage.getHeight();//200;//mainImage.getHeight();

			/* Get the size of the image */
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			int photoW = bmOptions.outWidth;
			int photoH = bmOptions.outHeight;
			
			/* Figure out which way needs to be reduced less */
			int scaleFactor = 1;
			if ((targetW > 0) || (targetH > 0)) {
				scaleFactor = Math.min(photoW/targetW, photoH/targetH)+1;	
			}
			Log.e("setPic", "scaleFactor="+String.valueOf(scaleFactor)+",photoW="+String.valueOf(photoW)+",targetW="+String.valueOf(targetW)); 
			/* Set bitmap options to scale the image decode target */
			bmOptions.inJustDecodeBounds = false;
			bmOptions.inSampleSize = scaleFactor;//scaleFactor;
			bmOptions.inPurgeable = true;
			//bmOptions.inScreenDensity=true;
			/* Decode the JPEG file into a Bitmap */
			Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			//Bitmap bitmap2 = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
			//Bitmap result;
			//bitmap = Bitmap.createScaledBitmap(bitmap, 300, 200, false);
			Log.e("setPic", "ok");
			//mImageBitmap = bitmap;
            //Bitmap bp =(Bitmap) extras.get("data");// setPic();
			//result=saveImage(bitmap,bitmap2,mode);
			mainImage.setImageBitmap(bitmap);
			//mainBit.setImageBitmap(result);
    		Log.e("setPic", "ok1"); 
			//return result;
	   }
	   @Override
	   public boolean onCreateOptionsMenu(Menu menu) {
	      // Inflate the menu; this adds items to the action bar if it is present.
	      getMenuInflater().inflate(R.menu.menu_share, menu);
	      return true;
	   }
	   @Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// Log.e("aaaaaaaaaaaaaaaaa",String.valueOf(item.getItemId()));
			switch (item.getItemId()) {
			case R.id.menu_item_undo:
				if (mCurrentPhotoPath==null) return true;
				fromMode=null;
				toMode=null;
				originalPic();
				return true;
			case R.id.menu_item_share:
				// HomePage();
				// Log.e("aaaaaaaaaaaaaaaaa","1");
				//String message = this.link;
//				Intent share = new Intent(Intent.ACTION_SEND);
//				share.setType("text/plain");
//				//share.putExtra(Intent.EXTRA_TEXT, message);
//				startActivity(Intent.createChooser(share, "Share Image"));
				// Log.e("aaaaaaaaaaaaaaaaa","2");
				//String path = Images.Media.insertImage(getContentResolver(), screenshot, "title", null);
				if (fromMode==null || mCurrentPhotoPath==null)
				{
					Toast.makeText(this.getBaseContext(), "Choose a picture for sharing!", Toast.LENGTH_LONG).show();
					return true;
				}
				currentPhotos=savePic(fromMode,toMode);
				//File imageFileToShare = new File(currentPhotos);
				//sendBroadcast(new Intent(Intent.EXTRA_STREAM,Uri.parse(currentPhotos)));//"file://" + Environment.getExternalStorageDirectory()
				//Log.e("ShareSaaaaaaaaaaaaaaaaaaaaa",currentPhotos);
				Uri screenshotUri = Uri.fromFile(currentFile);//parse
				//sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, screenshotUri));
				//Log.e("share", "3");
				final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
				//emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				emailIntent.setType("image/*");	
				emailIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
				//emailIntent.putExtra(Intent.EXTRA_TEXT, "My Photo!");
				
//				Intent openInChooser = new Intent(emailIntent);
//				openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, "com.huynv.socialphotos");
//				startActivity(openInChooser);
				//sharePhotos("facebook",currentPhotos,"text");
				//sharePhotos("twitter",currentPhotos,"text");
				startActivity(Intent.createChooser(emailIntent, "Share your photo."));
				//emailIntent.putExtra(Intent.EXTRA_TEXT, "My EQ scores are "+String.valueOf(totalPoints)+" points, Test with this game: https://play.google.com/store/apps/details?id=com.huynv.redblue");
				//emailIntent.setType("text/plain");
				
				return true;
			case R.id.menu_item_save:
				// HomePage();
				// Log.e("aaaaaaaaaaaaaaaaa","1");
				//String message = this.link;
				//Intent share = new Intent(Intent.ACTION_SEND);
				//share.setType("text/plain");
				//share.putExtra(Intent.EXTRA_TEXT, message);
				//startActivity(Intent.createChooser(share, "Share Image"));
				// Log.e("aaaaaaaaaaaaaaaaa","2");
				if (fromMode==null || mCurrentPhotoPath==null)
				{
					Toast.makeText(this.getBaseContext(), "Choose a picture!", Toast.LENGTH_LONG).show();
					return true;
				}
				currentPhotos=savePic(fromMode,toMode);
				sendBroadcast(new Intent(Intent.EXTRA_STREAM,Uri.parse(currentPhotos)));
				Toast.makeText(this.getBaseContext(), "Saved image at "+currentPhotos, Toast.LENGTH_LONG).show();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
	   private void sharePhotos(String nameApp, String imagePath,String message) {
		   try
			  {
			    List<Intent> targetedShareIntents = new ArrayList<Intent>();
			    Intent share = new Intent(android.content.Intent.ACTION_SEND);
			      share.setType("image/*");
			    List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
			    if (!resInfo.isEmpty()){
			      for (ResolveInfo info : resInfo) {
			          Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
			          targetedShare.setType("image/*"); // put here your mime type
			          if (info.activityInfo.packageName.toLowerCase().contains(nameApp) || info.activityInfo.name.toLowerCase().contains(nameApp)) {
			              targetedShare.putExtra(Intent.EXTRA_SUBJECT, "Share Photo");
			              targetedShare.putExtra(Intent.EXTRA_TEXT,message);
			              targetedShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath)) );
			              targetedShare.setPackage(info.activityInfo.packageName);
			              targetedShareIntents.add(targetedShare);
			          }
			      }
			      Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select image to share");
			      chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
			      startActivity(chooserIntent);
			    }
			  } catch(Exception e){
		        Log.v("VM","Exception while sending image on" + nameApp + " "+  e.getMessage());
		      }
		}
	   /** Create a file Uri for saving an image or video */
//	   private static Uri getOutputMediaFileUri(int type){
//	         return Uri.fromFile(getOutputMediaFile(type));
//	   }

//	   /** Create a File for saving an image or video */
//	   private static File getOutputMediaFile(int type){
//	       // To be safe, you should check that the SDCard is mounted
//	       // using Environment.getExternalStorageState() before doing this.
//
//	       File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
//	                 Environment.DIRECTORY_PICTURES), "MyCameraApp");
//	       // This location works best if you want the created images to be shared
//	       // between applications and persist after your app has been uninstalled.
//
//	       // Create the storage directory if it does not exist
//	       if (! mediaStorageDir.exists()){
//	           if (! mediaStorageDir.mkdirs()){
//	               Log.d("MyCameraApp", "failed to create directory");
//	               return null;
//	           }
//	       }
//
//	       // Create a media file name
//	       String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//	       File mediaFile;
//	       if (type == MEDIA_TYPE_IMAGE){
//	           mediaFile = new File(mediaStorageDir.getPath() + File.separator +
//	           "IMG_"+ timeStamp + ".jpg");
//	       } else if(type == MEDIA_TYPE_VIDEO) {
//	           mediaFile = new File(mediaStorageDir.getPath() + File.separator +
//	           "VID_"+ timeStamp + ".mp4");
//	       } else {
//	           return null;
//	       }
//
//	       return mediaFile;
//	   }   
	private Bitmap MapImage(Bitmap b1,Bitmap b2,PorterDuff.Mode modeOut,PorterDuff.Mode modeMain){//Mode.SRC_OVER//,String fileName
		//ImageView compositeImageView = (ImageView) findViewById(R.id.mainImage);
		Bitmap bitmap1=b1;//BitmapFactory.decodeResource(getResources(), R.drawable.hoa);
		Bitmap bitmap2=getARGBImage(bitmap1,modeMain);
		//Log.e("aa", "11111");
				//BitmapFactory.decodeResource(getResources(), R.drawable.h1);//getARGBImage();
//
//		 Bitmap bitmap1=BitmapFactory.decodeResource(getResources(), R.drawable.h1);
        //Bitmap filter2=BitmapFactory.decodeResource(getResources(), R.drawable.h3);
        Bitmap bitmap3=b2;//BitmapFactory.decodeResource(getResources(), R.drawable.thuy2);
        //Bitmap h3=BitmapFactory.decodeResource(getResources(), R.drawable.h3);
        //Log.e("aa", "22222");
//	
//		 BitmapFactory.Options opt = new BitmapFactory.Options();
//		 opt.inPreferredConfig = Config.ARGB_8888;

		 Bitmap resultingImage=Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(), bitmap1.getConfig());
		 //Log.e("aa", "33333");
		 Canvas canvas = new Canvas(resultingImage);
		 //Log.e("aa", "44444");
//		 
//		 // Drawing first image on Canvas
		 Paint paint = new Paint();
		 //Log.e("aa", "5555");
		 canvas.drawBitmap(bitmap2, 0, 0, paint);
		 //Log.e("aa", "66666");
		 // Drawing second image on the Canvas, with Xfermode set to XOR
		 paint.setXfermode(new PorterDuffXfermode(modeOut));//main is Mode.SCREEN
		 //Log.e("aa", "7777");
		 //resultingImage.eraseColor(Color.BLACK);
		 canvas.drawBitmap(bitmap3, 0, 0, paint);
		 //Log.e("aa", "88888");
		 //paint.setXfermode(new PorterDuffXfermode(Mode.ADD));
		 //resultingImage.eraseColor(Color.BLACK);
		 //canvas.drawBitmap(bitmap3, 0, 0, paint);		 
//		 
		 //Tra ve ket qua
		 //compositeImageView.setImageBitmap(resultingImage);
		 //storeImage(resultingImage,fileName);
		 return resultingImage;
		 
	}
	private Bitmap getARGBImage(Bitmap filter,PorterDuff.Mode mode)
	{
	    BitmapFactory.Options opt = new BitmapFactory.Options();
	    opt.inPreferredConfig = Config.ARGB_8888;
	 
	    Bitmap red = BitmapFactory.decodeResource(getResources(),
	            R.drawable.red, opt);
	    Bitmap green = BitmapFactory.decodeResource(getResources(),
	            R.drawable.green, opt);
	    Bitmap blue = BitmapFactory.decodeResource(getResources(),
	            R.drawable.blue, opt);
	    Bitmap alphaGray =filter;// BitmapFactory.decodeResource(getResources(),R.drawable.h22, opt);
	 
	    int width = alphaGray.getWidth();
	    int height = alphaGray.getHeight();
	 
	    Bitmap result = Bitmap.createBitmap(width, height, Config.ARGB_8888);
	    result.eraseColor(Color.BLACK);
	 
	    Paint redP = new Paint();
	    redP.setShader(new BitmapShader(red, TileMode.CLAMP, TileMode.CLAMP));
	    redP.setColorFilter(new PorterDuffColorFilter(Color.RED, Mode.MULTIPLY));
	    redP.setXfermode(new PorterDuffXfermode(Mode.SCREEN));
	 
	    Paint greenP = new Paint();
	    greenP.setShader(new BitmapShader(green, TileMode.CLAMP,TileMode.CLAMP));
	    greenP.setColorFilter(new PorterDuffColorFilter(Color.GREEN,Mode.MULTIPLY));
	    greenP.setXfermode(new PorterDuffXfermode(Mode.SCREEN));
	 
	    Paint blueP = new Paint();
	    blueP.setShader(new BitmapShader(blue, TileMode.CLAMP, TileMode.CLAMP));
	    blueP.setColorFilter(new PorterDuffColorFilter(Color.BLUE,Mode.MULTIPLY));
	    blueP.setXfermode(new PorterDuffXfermode(Mode.SCREEN));
	 
	    Canvas c = new Canvas(result);
	    c.drawRect(0, 0, width, height, redP);
	    c.drawRect(0, 0, width, height, greenP);
	    c.drawRect(0, 0, width, height, blueP);
	 
	    Bitmap alpha = Bitmap.createBitmap(width, height, Config.ARGB_8888);
	    int[] alphaPix = new int[width * height];
	    alphaGray.getPixels(alphaPix, 0, width, 0, 0, width, height);
	 
	    int count = width * height;
	    for (int i = 0; i < count; ++i)
	    {
	        alphaPix[i] = alphaPix[i] << 8;
	    }
	    alpha.setPixels(alphaPix, 0, width, 0, 0, width, height);
	 
	    Paint alphaP = new Paint();
	    alphaP.setAntiAlias(true);
	    //alphaP.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
	    alphaP.setXfermode(new PorterDuffXfermode(mode));
	 
	    c.drawBitmap(alpha, 0, 0, alphaP);
	 
	    red.recycle();
	    green.recycle();
	    blue.recycle();
	    alphaGray.recycle();
	    alpha.recycle();
	 
	    return result;
	}

	private String storeImage(Bitmap image) {
		String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
        File pictureFile = getOutputMediaFile(timeStamp);
        if (pictureFile == null) {
            //Log.d(TAG,
                    //"Error creating media file, check storage permissions: ");// e.getMessage());
            return "";
        } 
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
        } catch (Exception e) {
            //Log.d(TAG, "File not found: " + e.getMessage());
        }  
        currentFile=pictureFile;
        return pictureFile.getAbsolutePath();
    }
    private  File getOutputMediaFile(String fileName){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this. 
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Pictures/SocialPhotosEditor/"); 

        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        } 
        // Create a media file name
        //String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
        File mediaFile;
            String mImageName=fileName+".png";
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
        return mediaFile;
    }
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}

}
